﻿from django.http import HttpRequest, HttpResponse

from django.views.decorators.csrf import csrf_exempt

from django.conf import settings

from ChatGPT_SP_Server.userdata import results 

import json
# import os
# import openai
import requests

@csrf_exempt
def register(request: HttpRequest) -> HttpResponse:
    if request.method == 'POST':
        try:
            rawRequestBody = request.body.decode('utf-8')
                    	
            # 获取POST请求的JSON数据
            json_data = json.loads(rawRequestBody)
 
            # 处理JSON数据
            user_name = json_data[0]
            pass_word = json_data[1]
            mail = json_data[2]
            phone = json_data[3]
            
            result = {
                "UserName": user_name,
                "Password": pass_word,
                "Mail": mail,
                "Phone": phone
            }
            global results
            results.append(result)
            result_json = json.dumps(results)
            with open("results.txt", "w") as f:
                f.write(result_json)

            return HttpResponse("成功")

        except Exception as ex:

            return HttpResponse(status=500, content=json.dumps({'message': str(ex)}), content_type='application/json')

    return HttpResponse(status=405, content=json.dumps({'message': 'Method Not Allowed'}), content_type='application/json')


@csrf_exempt  # disable CSRF protection since we are just doing a simple API call
def login_sp(request):
    if request.method == 'POST':
        try:
          
            rawRequestBody = request.body.decode('utf-8')
          
            # 获取POST请求的JSON数据
            json_data = json.loads(rawRequestBody)

            # 处理JSON数据
            user_name = json_data[0]
            pass_word = json_data[1]
            return_value = "用户名不存在"
            global results
            # decode password if necessary
            if len(results) > 0:
                for record in results:
                    if record["UserName"] == user_name:
                        if record["Password"] == pass_word:
                            return_value = "成功"
                        else:
                            return_value = "密码错误"
                        break
            return HttpResponse(return_value)
        except Exception as ex:
            return HttpResponse(status=500, content=json.dumps({'message': str(ex)}), content_type='application/json')
    else:
        return HttpResponse(status=405, content=json.dumps({'message': 'Method Not Allowed'}), content_type='application/json')

@csrf_exempt
def try_connection(request):
    return HttpResponse("连上了")

@csrf_exempt
def listmodels(request):
    # if request.method == 'POST':
    try:
        rawRequestBody = request.body.decode('utf-8')
        # 解析 JSON
        data = json.loads(rawRequestBody)

        # Replace with your actual API key
        OPENAI_API_KEY = data[0]    

        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {OPENAI_API_KEY}"
        }

        response = requests.get("https://api.openai.com/v1/models", headers=headers)
        return HttpResponse(response) 
    except Exception as e:
        return HttpResponse(status=500, content=e)
    # else:
    #     return HttpResponse(status=405, content="Only POST requests are allowed")    


@csrf_exempt
def SendChatMessage(request):
    if request.method == 'POST':
        try:
            double_temperature, double_topP, int_number, str_user,str_model,int_maxTokens = None, None, None, None, None, None
            list_stops, dict_logitBias = None, None
            rawRequestBody = request.body.decode('utf-8')
            # 解析 JSON
            data = json.loads(rawRequestBody)

     
            key = data[0]
            parameters = data[1]
            paras = parameters
            if "temperature" in paras:
                double_temperature = float(paras["temperature"])
            if "topP" in paras:
                double_topP = float(paras["topP"])
            if "number" in paras:
                int_number = int(paras["number"])
            if "model" in paras:
                str_model = paras["model"]
            if "maxTokens" in paras:
                int_maxTokens = paras["maxTokens"]
            if "user" in paras:
                str_user = paras["user"]
            if "stops" in paras:
                list_stops = paras["stops"]
            if "logitBias" in paras:
                dict_logitBias = paras["logitBias"]
            message = data[2]
            result = ""
            url = "https://api.openai.com/v1/chat/completions"
            headers = {
                "Content-Type": "application/json",
                "Authorization": f"Bearer {key}"
            }

            data = {
                "model": "gpt-3.5-turbo",
                "messages": [{"role": "user", "content": "Hello!"}]
            }

            response = requests.post(url, headers=headers, json=data)
            completion = response.json()
            # openai.api_key = key
            # completion = openai.ChatCompletion.create(
            # model=str_model,
            # messages=message,
            # temperature = double_temperature,
            # top_p = double_topP,
            # n = int_number,
            # stop = list_stops,
            #  max_tokens = int_maxTokens,
            # logit_bias = dict_logitBias,
            # user = str_user
            # )

            # # 处理 message 和 model，这里只是一个示例
            result = completion.choices[0].message+"\n"

            if "usage" in completion :
                if "prompt_tokens" in completion.usage :
                    result = result + "\nprompt_tokens:" + completion.usage.prompt_tokens
                if "completion_tokens" in completion.usage :
                    result = result + "\ncompletion_tokens:" + completion.usage.completion_tokens
                if "total_tokens" in completion.usage :
                    result = result + "\ntotal_tokens:" + completion.usage.total_tokens
            return HttpResponse(result) 
        except Exception as e:
            return HttpResponse(status=500, content=e)
    else:
        return HttpResponse(status=405, content="Only POST requests are allowed")